<template>
  <div class="supplier-detail-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <el-button type="default" icon="ArrowLeft" @click="handleBack">返回列表</el-button>
      <h1>供应商详情</h1>
      <div class="header-actions">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon> 编辑
        </el-button>
        <el-button
          :type="supplierInfo.status === 1 ? 'danger' : 'success'"
          @click="handleStatusChange"
        >
          <el-icon>{{ supplierInfo.status === 1 ? <Close /> : <Check /> }}</el-icon>
          {{ supplierInfo.status === 1 ? '禁用' : '启用' }}
        </el-button>
      </div>
    </div>

    <!-- 供应商基本信息卡片 -->
    <el-card class="base-info-card">
      <div class="card-header">
        <h2>基本信息</h2>
        <div class="supplier-status">
          <el-tag :type="supplierInfo.status === 1 ? 'success' : 'danger'">
            {{ supplierInfo.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-item">
          <span class="label">供应商编码：</span>
          <span class="value">{{ supplierInfo.code }}</span>
        </div>
        <div class="info-item">
          <span class="label">供应商名称：</span>
          <span class="value">{{ supplierInfo.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">统一社会信用代码：</span>
          <span class="value">{{ supplierInfo.creditCode }}</span>
        </div>
        <div class="info-item">
          <span class="label">成立日期：</span>
          <span class="value">{{ supplierInfo.establishDate }}</span>
        </div>
        <div class="info-item">
          <span class="label">注册资本：</span>
          <span class="value">{{ supplierInfo.registeredCapital }} 万元</span>
        </div>
        <div class="info-item">
          <span class="label">企业类型：</span>
          <span class="value">{{ supplierInfo.enterpriseType }}</span>
        </div>
        <div class="info-item">
          <span class="label">经营范围：</span>
          <span class="value">{{ supplierInfo.businessScope }}</span>
        </div>
        <div class="info-item">
          <span class="label">所属行业：</span>
          <span class="value">{{ supplierInfo.industry }}</span>
        </div>
      </div>
    </el-card>

    <!-- 联系信息卡片 -->
    <el-card class="contact-info-card">
      <div class="card-header">
        <h2>联系信息</h2>
      </div>

      <div class="info-grid">
        <div class="info-item">
          <span class="label">联系人：</span>
          <span class="value">{{ supplierInfo.contactPerson }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系电话：</span>
          <span class="value">{{ supplierInfo.contactPhone }}</span>
        </div>
        <div class="info-item">
          <span class="label">电子邮箱：</span>
          <span class="value">{{ supplierInfo.email }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系地址：</span>
          <span class="value">{{ supplierInfo.provinceName }}{{ supplierInfo.cityName }}{{ supplierInfo.address }}</span>
        </div>
        <div class="info-item">
          <span class="label">邮政编码：</span>
          <span class="value">{{ supplierInfo.zipCode }}</span>
        </div>
        <div class="info-item">
          <span class="label">网站地址：</span>
          <span class="value">{{ supplierInfo.website }}</span>
        </div>
      </div>
    </el-card>

    <!-- 银行账户信息卡片 -->
    <el-card class="bank-info-card">
      <div class="card-header">
        <h2>银行账户信息</h2>
      </div>

      <div class="info-grid">
        <div class="info-item">
          <span class="label">开户银行：</span>
          <span class="value">{{ supplierInfo.bankName }}</span>
        </div>
        <div class="info-item">
          <span class="label">银行账号：</span>
          <span class="value">{{ supplierInfo.bankAccount }}</span>
        </div>
        <div class="info-item">
          <span class="label">开户名：</span>
          <span class="value">{{ supplierInfo.accountName }}</span>
        </div>
        <div class="info-item">
          <span class="label">联行号：</span>
          <span class="value">{{ supplierInfo.bankCode }}</span>
        </div>
      </div>
    </el-card>

    <!-- 备注信息卡片 -->
    <el-card class="remark-card" v-if="supplierInfo.remark">
      <div class="card-header">
        <h2>备注信息</h2>
      </div>
      <div class="remark-content">{{ supplierInfo.remark }}</div>
    </el-card>

    <!-- 操作历史卡片 -->
    <el-card class="operation-history-card">
      <div class="card-header">
        <h2>操作历史</h2>
      </div>

      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in supplierInfo.operationHistory"
          :key="index"
          :timestamp="item.operateTime"
          :color="index === 0 ? 'green' : 'blue'"
        >
          <div class="timeline-content">
            <div class="operate-desc">{{ item.operateDesc }}</div>
            <div class="operate-user">操作人：{{ item.operateUser }}</div>
            <div class="operate-remark" v-if="item.remark">备注：{{ item.remark }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, Edit, Check, Close } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义操作历史接口
interface OperationHistory {
  operateTime: string;
  operateDesc: string;
  operateUser: string;
  remark?: string;
}

// 定义供应商详情接口
interface SupplierDetail {
  id: string;
  code: string;
  name: string;
  status: 0 | 1;
  creditCode: string;
  establishDate: string;
  registeredCapital: number;
  enterpriseType: string;
  businessScope: string;
  industry: string;
  contactPerson: string;
  contactPhone: string;
  email: string;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  address: string;
  zipCode: string;
  website: string;
  bankName: string;
  bankAccount: string;
  accountName: string;
  bankCode: string;
  remark?: string;
  createTime: string;
  updateTime: string;
  operationHistory: OperationHistory[];
}

// 状态管理
const loading = ref(true);
const supplierInfo = ref<SupplierDetail>({} as SupplierDetail);
const route = useRoute();
const router = useRouter();
const supplierId = route.params.id as string;

// 返回供应商列表
const handleBack = () => {
  router.push({ name: 'SupplierList' });
};

// 编辑供应商
const handleEdit = () => {
  router.push({ name: 'SupplierEdit', params: { id: supplierId } });
};

// 切换供应商状态（启用/禁用）
const handleStatusChange = async () => {
  const newStatus = supplierInfo.value.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '启用' : '禁用';
  const confirmMessage = `确定要${statusText}供应商【${supplierInfo.value.name}】吗？`;

  try {
    await ElMessageBox.confirm(confirmMessage, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 模拟API请求
    loading.value = true;
    await new Promise(resolve => setTimeout(resolve, 800));

    // 更新本地状态
    supplierInfo.value.status = newStatus;
    // 添加操作历史
    supplierInfo.value.operationHistory.unshift({
      operateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      operateDesc: `供应商状态更新为${statusText}`,
      operateUser: '当前用户'
    });

    ElMessage.success(`供应商已${statusText}`);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`供应商${statusText}失败`);
      console.error(`供应商${statusText}失败:`, error);
    }
  } finally {
    loading.value = false;
  }
};

// 获取供应商详情数据
const fetchSupplierDetail = async () => {
  loading.value = true;
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 生成模拟数据
    const now = new Date();
    const threeMonthsAgo = new Date(now.getTime() - 3 * 30 * 24 * 60 * 60 * 1000);
    const twoMonthsAgo = new Date(now.getTime() - 2 * 30 * 24 * 60 * 60 * 1000);
    const oneMonthAgo = new Date(now.getTime() - 1 * 30 * 24 * 60 * 60 * 1000);

    supplierInfo.value = {
      id: supplierId,
      code: `SP${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`,
      name: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      status: Math.random() > 0.2 ? 1 : 0,
      creditCode: `91${Math.floor(Math.random() * 100000000000000000).toString().padStart(17, '0')}`,
      establishDate: new Date(2000 + Math.floor(Math.random() * 20), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28)).toISOString().slice(0, 10),
      registeredCapital: Math.floor(Math.random() * 10000) + 100,
      enterpriseType: ['有限责任公司', '股份有限公司', '个体工商户', '合伙企业'][Math.floor(Math.random() * 4)],
      businessScope: ['办公用品销售；计算机软硬件及辅助设备零售；电子产品销售；家具销售；日用百货销售；五金产品零售', '信息技术咨询服务；软件开发；数据处理服务；计算机系统服务；互联网信息服务', '建筑材料销售；机械设备销售；化工产品销售（不含许可类化工产品）；金属材料销售'][Math.floor(Math.random() * 3)],
      industry: ['批发和零售业', '信息传输、软件和信息技术服务业', '制造业', '建筑业'][Math.floor(Math.random() * 4)],
      contactPerson: `联系人${Math.floor(Math.random() * 100)}`,
      contactPhone: `13${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
      email: `contact${Math.floor(Math.random() * 1000)}@example.com`,
      provinceCode: ['330000', '110000', '310000', '440000'][Math.floor(Math.random() * 4)],
      provinceName: ['浙江省', '北京市', '上海市', '广东省'][Math.floor(Math.random() * 4)],
      cityCode: '330100',
      cityName: '杭州市',
      address: `测试地址${Math.floor(Math.random() * 100)}号`,
      zipCode: `${Math.floor(Math.random() * 1000000).toString().padStart(6, '0')}`,
      website: `http://www.supplier${Math.floor(Math.random() * 1000)}.com`,
      bankName: ['中国工商银行', '中国建设银行', '中国银行', '中国农业银行'][Math.floor(Math.random() * 4)] + `${Math.floor(Math.random() * 100)}支行`,
      bankAccount: `6222${Math.floor(Math.random() * 1000000000000).toString().padStart(12, '0')}`,
      accountName: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      bankCode: `${Math.floor(Math.random() * 1000000).toString().padStart(12, '0')}`,
      remark: Math.random() > 0.5 ? '这是一个测试供应商，用于系统演示。该供应商主要提供办公设备和IT产品。' : undefined,
      createTime: threeMonthsAgo.toISOString().slice(0, 19).replace('T', ' '),
      updateTime: oneMonthAgo.toISOString().slice(0, 19).replace('T', ' '),
      operationHistory: [
        {
          operateTime: threeMonthsAgo.toISOString().slice(0, 19).replace('T', ' '),
          operateDesc: '创建供应商',
          operateUser: '系统管理员'
        },
        {
          operateTime: twoMonthsAgo.toISOString().slice(0, 19).replace('T', ' '),
          operateDesc: '更新供应商联系信息',
          operateUser: '张三',
          remark: '更新了联系电话和邮箱'
        },
        {
          operateTime: oneMonthAgo.toISOString().slice(0, 19).replace('T', ' '),
          operateDesc: '供应商状态更新为启用',
          operateUser: '李四'
        }
      ]
    };
  } catch (error) {
    ElMessage.error('获取供应商详情失败');
    console.error('获取供应商详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchSupplierDetail();
});
</script>

<style scoped lang="scss">
.supplier-detail-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.base-info-card,
.contact-info-card,
.bank-info-card,
.remark-card,
.operation-history-card {
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px 20px;
}

.info-item {
  display: flex;
}

.label {
  color: #606266;
  width: 120px;
  flex-shrink: 0;
}

.value {
  flex-grow: 1;
  word-break: break-all;
}

.remark-content {
  line-height: 1.6;
  white-space: pre-wrap;
}

.timeline-content {
  padding: 5px 0;
}

.operate-desc {
  font-weight: 500;
  margin-bottom: 3px;
}

.operate-user,
.operate-remark {
  font-size: 12px;
  color: #606266;
  margin-bottom: 2px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .supplier-detail-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>